package k3.utils
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;	
	public class INIFile
	{
		public static var path:String;
		private static var _encode:String;
		private static var data_str:String;
		private static var data_result:Object;
		public  function INIFile()
		{
			
		}
		
		public static function phrase(INIPath:String,encode:String="utf-8"):void
		{
			path=INIPath;
			_encode=encode;
			
			data_str=openAsTxt( File.applicationDirectory.resolvePath(path),_encode);
			
			data_result=parseINIString(data_str);
		}
		public static function ReadValue( Section:String, Key:String):String
		{
			
			return data_result[Section][Key];
		}
		
		private static function parseINIString(data_:String):Object{
			var value:Object = {};
			var lines:Array = data_.split(/\r\n|\r|\n/);
			var section:String = null;
			for(var i:uint=0;i<lines.length;i++)
			{
				var line:String=lines[i];
				if(line.length==0)continue;
				var re1:RegExp=/^\s*\s*([^]*)\s*\]\s*$/;
				var re2:RegExp=/^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/;
				
				if(re2.test(line)){
					
					var match:Array = line.match(re2);
					
					
					if(section){
						
						value[section][match[1]] = match[2];
					}else{
						value[match[1]] = match[2];
						
					}
				}else if(re1.test(line)){
					var match:Array = line.match(re1);
					
					
					section =replaceSection( match[0]);
					value[section] = {};
					
					
				}else if(line.length == 0 && section){
					
					
					section = null;
				};
			}
			
			return value;
			
		}
		
		private static function replaceSection(value:String):String
		{
			var index0:int=value.indexOf('[');
			var index1:int=value.indexOf(']');
			value=value.substring(index0+1,index1);
			return value;
		}
		
		public static  function openFileToByte(file:File):ByteArray
		{
			if (!file || !file.exists)
			{
				return null;
			}
			var stream:FileStream = new FileStream();
			stream.open(file, FileMode.READ);
			var fileDate:ByteArray = new ByteArray();
			stream.readBytes(fileDate, 0, stream.bytesAvailable);
			stream.close();
			return fileDate;
		}
		
		public static function getFileEncode(bytes:ByteArray):String
		{
			var b0:int = bytes.readUnsignedByte();
			
			
			var b1:int = bytes.readUnsignedByte();
			
			bytes.position = 0;
			if (b0 == 0xFF && b1 == 0xFE)
			{
				return "unicode";
			}
			else if (b0 == 0xFE && b1 == 0xFF)
			{
				return "unicodeFFFE";
			}
			else if (b0 == 0xEF && b1 == 0xA0)
			{
				return "utf-8";
			}
			else if (b0 == 0xE6 && b1 == 0xA0)
			{
				return "utf-8";
			}
			else
			{
				return "gb2312"
			}
			
		}
		
		
		public static function openAsTxt(file:File,type:String):String
		{
			var b:ByteArray = openFileToByte(file);
			if (!b)
			{
				return null;
			}
			
			b.position = 0;
			type=type ? type : getFileEncode(b);
		
			b.position = 0;
			return b.readMultiByte(b.bytesAvailable, type);
		}
		
	}
}